﻿/**
 * 通用js方法封装处理
 * Copyright (c) 2019 liuen
 */
import { PopupManager } from 'element-ui/lib/utils/popup'

export default {
  /**
   * 获取最大z-index值
   * @returns {*}
   */
  getMaxIndex() {
    return PopupManager.nextZIndex()
  },
  /**
   * 添加日期范围
   * @param params
   * @param dateRange
   * @returns {*}
   */
  addDateRange(params, dateRange) {
    let createTimeBegin = ''
    let createTimeEnd = ''
    if (dateRange !== null && dateRange !== '') {
      createTimeBegin = dateRange[0]
      createTimeEnd = dateRange[1]
    }
    return {
      ...params,
      createTimeBegin,
      createTimeEnd
    }
  },
  /**
   * 回显数据字典
   * @param datas
   * @param value
   * @returns {string}
   */
  getDictValueName(dictValues, dictValueCode) {
    let dictValueName = ''
    dictValues.some(dictValue => {
      if (dictValue.dictValueCode === dictValueCode) {
        dictValueName = dictValue.dictValueName
        return true
      }
    })
    return dictValueName
  },
  /**
   * 回显数据字典（字符串数组）
   * @param datas
   * @param value
   * @param separator
   * @returns {string}
   */
  getDictValueNames(datas, value, separator) {
    var actions = []
    var currentSeparator = undefined === separator ? ',' : separator
    var temp = value.split(currentSeparator)
    Object.keys(value.split(currentSeparator)).some((val) => {
      Object.keys(datas).some((key) => {
        if (datas[key].dictValue === ('' + temp[val])) {
          actions.push(datas[key].dictLabel + currentSeparator)
        }
      })
    })
    return actions.join('').substring(0, actions.join('').length - 1)
  },
  /**
   * 通用下载方法
   * @param fileName
   */
  download(url) {
    window.open(url)
  },
  /**
   * 字符串格式化(%s )
   * @param str
   * @returns {*}
   */
  sprintf(str) {
    const args = arguments
    let flag = true
    let i = 1
    str = str.replace(/%s/g, function() {
      const arg = args[i++]
      if (typeof arg === 'undefined') {
        flag = false
        return ''
      }
      return arg
    })
    return flag ? str : ''
  },
  /**
   * 转换字符串，undefined,null等转化为''
   * @param str
   * @returns {string|*}
   */
  praseStrEmpty(str) {
    if (!str || str === 'undefined' || str === 'null') {
      return ''
    }
    return str
  },
  /**
   * 构造树型结构数据
   * @param data 数据源
   * @param id id字段 默认 'id'
   * @param pid 父节点字段 默认 'pid'
   * @param children 孩子节点字段 默认 'children'
   * @param rootId 根Id 默认 0
   * @returns {*}
   */
  list2Tree(data, id = 'id', pid = 'pid', children = 'children', rootId) {
    // 没有指定根节点ID时，取数据中PID的最小值作为根节点ID
    rootId = rootId || Math.min.apply(Math, data.map(node => { return node[pid] })) || 0
    // 对源数据深度克隆，组装数据时不污染源数据
    const cloneData = JSON.parse(JSON.stringify(data))
    // 循环所有节点，封装各节点的子节点数组，并返回根节点的子节点数组
    const treeData = cloneData.filter(parentNode => {
      // 返回当前节点的的子节点数组
      const childrenArr = cloneData.filter(childrenNode => {
        return parentNode[id] === childrenNode[pid]
      })
      childrenArr.length > 0 ? parentNode[children] = childrenArr : []
      // 返回根节点的子节点数组
      return Number(parentNode[pid]) === rootId
    })
    return treeData.length !== 0 ? treeData : data
  },
  addDynamicRoute(routeParams, router) {
    // 组装路由名称, 并判断是否已添加, 如是: 则直接跳转
    var routeName = routeParams.routeName
    var dynamicRoute = window.SITE_CONFIG['dynamicRoutes'].filter(item => item.name === routeName)[0]
    if (dynamicRoute) {
      return router.push({ name: routeName, params: routeParams.params })
    }
    // 否则: 添加并全局变量保存, 再跳转
    dynamicRoute = {
      path: routeName,
      component: (resolve) => require([`@/views/${routeParams.path}`], resolve),
      name: routeName,
      meta: {
        ...window.SITE_CONFIG['contentTabDefault'],
        menuId: routeParams.menuId,
        title: `${routeParams.title}`
      }
    }
    router.addRoutes([
      {
        name: `main-dynamic__${dynamicRoute.name}`,
        children: [dynamicRoute]
      }
    ])
    window.SITE_CONFIG['dynamicRoutes'].push(dynamicRoute)
    router.push({ name: dynamicRoute.name, params: routeParams.params })
  }
}
